<template>
  <div>
    <div style="margin-bottom: 10px;">
      <el-input style="width:200px" placeholder="查询姓名" v-model="name"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
      <el-button type="success" @click="addStudent">新增</el-button>
    </div>

    <el-table :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color:'#666'}">
      <el-table-column prop="id" label="序号" width="70"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column label="头像">
        <template v-slot="scope">
          <el-image style="width: 50px; height: 50px; border-radius: 50%;" v-if="scope.row.avatar" :src="scope.row.avatar"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="scope">
          <el-button size="mini" type="primary" @click="editStudent(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteStudent(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--编辑对话框 -->
    <el-dialog :visible.sync="dialogVisible1" title="学生信息">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-autocomplete
              v-model="formData.username"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入姓名"
              @select="handleSelect"
              @input="onNameInput"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="formData.avatar"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="formData.role"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editStudentMsg">保存</el-button>
        </span>
      </template>
    </el-dialog>
<!--    教师关联学生-->
    <el-dialog :visible.sync="dialogVisible2" title="学生信息">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-autocomplete
              v-model="formData.username"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入姓名"
              @select="handleSelect"
              @input="onNameInput"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-input v-model="formData.avatar"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="formData.role"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStudent">关联</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [], // 学生数据
      name: '', // 查询条件：姓名
      teacherId: JSON.parse(localStorage.getItem('honey-user')).id, // 当前教师的ID
      dialogVisible1: false, // 对话框显示状态
      dialogVisible2: false,
      formData: {}, // 表单数据
      teacherName:JSON.parse(localStorage.getItem('honey-user')).name,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      searchResults: [] // 模糊查询结果
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      // 调用后端接口，查询教师指导的学生信息
      this.$request.get('/api/teacher/students', {
        params: {
          teacherId: this.teacherId,
          name: this.name
        }
      }).then(res => {
        this.tableData = res;
        console.log(res)
      });
    },
    reset() {
      this.name = '';
      this.load();
    },
    addStudent() {
      this.formData = {  }; // 确保新增时 id 为空
      this.dialogVisible2 = true;
    },
    editStudent(row) {
      this.formData = { ...row };
      this.dialogVisible1 = true;
    },
    deleteStudent(id) {
      this.$confirm('确定要删除该学生信息吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$request.get(`/api/teacher/delStudents`,{params:{
            studentId:id,
            teacherId:this.teacherId
          }
        }).then(() => {

          this.$message.success('删除成功');
          this.load();
        }).catch(() => {
          this.$message.error('删除失败');
        });
      }).catch(() => {});
    },
    //编辑学生信息
    editStudentMsg(){
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const apiUrl = `/api/teacher/students/${this.formData.id}`;
          const method =  'put';
          this.$request[method](apiUrl, {
            user: {...this.formData},
            teacherId: this.teacherId,
            teacherName:this.teacherName
          }).then(() => {
            this.$message.success( '编辑成功');
            this.dialogVisible1 = false;
            this.load();
          }).catch(() => {
            this.$message.error('编辑失败');
          });
        }
      });
    },
    //关联学生信息
    saveStudent() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {

          const apiUrl = '/api/teacher/addStudents';
          const method = 'post';

          this.$request[method](apiUrl, {
            user: {...this.formData},
            teacherId: this.teacherId,
            teacherName:this.teacherName
          }).then(() => {
            this.$message.success( '关联成功');
            this.dialogVisible2 = false;
            this.load();
          }).catch(() => {
            this.$message.error( '关联失败');
          });
        }
      });
    },
    //新增学生中输入学生姓名下拉框显示学生名字
    querySearchAsync(queryString, cb) {
      if (!queryString) {
        cb([]);
        return;
      }
      this.$request.get('/user/addTea', {
        params: {
          itme: queryString
        }
      }).then(res => {
        const results = res.data.map(item => ({
          value: item.name,
          id: item.id,
          username: item.username,
          phone: item.phone,
          email: item.email,
          avatar: item.avatar,
          role: item.role
        }));
        cb(results);
      });
    },
    handleSelect(item) {

        this.formData = {
          username: item.username,
          name: item.value,
          phone: item.phone,
          email: item.email,
          avatar: item.avatar,
          role: item.role
        };
        this.formData.id = item.id;
    },
    onNameInput(value) {
      console.log(value); // 可以保留用于调试
    }
  }
};
</script>

<style scoped>
/* 样式可以根据需要调整 */
</style>



